package com.example.pceb.controller;

import com.example.pceb.entity.*;
import com.example.pceb.service.*;
import com.example.pceb.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/subsidy")
public class SubsidyController {

    // 添加日志记录器
    private static final Logger logger = LoggerFactory.getLogger(SubsidyController.class);

    private final HighSkillTrainingService highSkillService;
    private final AwardProjectService awardProjectService;
    private final StartupSocialInsuranceService socialInsuranceService;

    @Autowired
    public SubsidyController(HighSkillTrainingService highSkillService,
                             AwardProjectService awardProjectService,
                             StartupSocialInsuranceService socialInsuranceService) {
        this.highSkillService = highSkillService;
        this.awardProjectService = awardProjectService;
        this.socialInsuranceService = socialInsuranceService;
    }

    /* ======================= 高技能人才培训补贴接口 ======================= */

    // 保存高技能人才培训补贴表单
    @PostMapping("/high-skill/save")
    public Result<Integer> saveHighSkill(@RequestBody HighSkillTrainingSubsidy form) {
        logger.info("===== 接收保存请求 =====");
        logger.info("请求路径: /high-skill/save");
        logger.info("请求数据: {}", form);

        try {
            highSkillService.saveForm(form);
            logger.info("保存成功，返回ID: {}", form.getId());
            return Result.success(form.getId());
        } catch (Exception e) {
            logger.error("保存失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    @PostMapping("/high-skill/submit-direct")
    public Result<Void> submitHighSkill(@RequestBody HighSkillTrainingSubsidy form) {
        logger.info("===== 接收提交请求 =====");
        logger.info("请求路径: /high-skill/submit-direct");
        logger.info("请求数据: {}", form);

        try {
            highSkillService.submitForm(form);
            logger.info("提交成功");
            return Result.success();
        } catch (Exception e) {
            logger.error("提交失败", e);
            return Result.error("提交失败: " + e.getMessage());
        }
    }

    // 获取用户的高技能人才培训补贴表单列表
    @GetMapping("/high-skill/list/{username}")
    public Result getHighSkillList(@PathVariable String username) {
        try {
            List<HighSkillTrainingSubsidy> list = highSkillService.getFormsByUsername(username);
            return Result.success(list);
        } catch (Exception e) {
            logger.error("获取高技能列表失败: {}", e.getMessage());
            return Result.error("获取列表失败: " + e.getMessage());
        }
    }

    // 获取高技能人才培训补贴表单详情
    @GetMapping("/high-skill/{id}")
    public Result getHighSkillDetail(@PathVariable Integer id) {
        try {
            HighSkillTrainingSubsidy form = highSkillService.getFormById(id);
            if (form == null) {
                logger.warn("高技能表单不存在: ID={}", id);
                return Result.error("表单不存在");
            }
            return Result.success(form);
        } catch (Exception e) {
            logger.error("获取高技能详情失败: {}", e.getMessage());
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    // 删除高技能人才培训补贴表单
    @DeleteMapping("/high-skill/{id}")
    public Result deleteHighSkill(@PathVariable Integer id) {
        try {
            highSkillService.deleteForm(id);
            logger.info("删除高技能表单成功: ID={}", id);
            return Result.success();
        } catch (Exception e) {
            logger.error("删除高技能表单失败: {}", e.getMessage());
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /* ======================= 获奖项目启动资金补贴接口 ======================= */

    // 保存获奖项目启动资金补贴表单
    @PostMapping("/award-project/save")
    public Result saveAwardProject(@RequestBody AwardProjectSubsidy form) {
        logger.info("保存获奖项目表单: {}", form);
        try {
            awardProjectService.saveForm(form);
            logger.info("保存成功，返回ID: {}", form.getId());
            return Result.success(form.getId());
        } catch (Exception e) {
            logger.error("保存获奖项目失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    // 提交获奖项目启动资金补贴表单
    @PostMapping("/award-project/submit-direct")
    public Result submitAwardProject(@RequestBody AwardProjectSubsidy form) {
        logger.info("提交获奖项目表单: {}", form);
        try {
            awardProjectService.submitForm(form);
            logger.info("提交成功");
            return Result.success();
        } catch (Exception e) {
            logger.error("提交获奖项目失败", e);
            return Result.error("提交失败: " + e.getMessage());
        }
    }

    // 获取用户的获奖项目启动资金补贴表单列表
    @GetMapping("/award-project/list/{username}")
    public Result getAwardProjectList(@PathVariable String username) {
        try {
            List<AwardProjectSubsidy> list = awardProjectService.getFormsByUsername(username);
            return Result.success(list);
        } catch (Exception e) {
            logger.error("获取获奖项目列表失败: {}", e.getMessage());
            return Result.error("获取列表失败: " + e.getMessage());
        }
    }

    // 获取获奖项目启动资金补贴表单详情
    @GetMapping("/award-project/{id}")
    public Result getAwardProjectDetail(@PathVariable Integer id) {
        try {
            AwardProjectSubsidy form = awardProjectService.getFormById(id);
            if (form == null) {
                logger.warn("获奖项目表单不存在: ID={}", id);
                return Result.error("表单不存在");
            }
            return Result.success(form);
        } catch (Exception e) {
            logger.error("获取获奖项目详情失败: {}", e.getMessage());
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    // 删除获奖项目启动资金补贴表单
    @DeleteMapping("/award-project/{id}")
    public Result deleteAwardProject(@PathVariable Integer id) {
        try {
            awardProjectService.deleteForm(id);
            logger.info("删除获奖项目表单成功: ID={}", id);
            return Result.success();
        } catch (Exception e) {
            logger.error("删除获奖项目失败: {}", e.getMessage());
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /* ======================= 初创企业社会保险补贴接口 ======================= */

    // 保存初创企业社会保险补贴表单
    @PostMapping("/startup-social/save")
    public Result saveStartupSocial(@RequestBody StartupSocialInsuranceSubsidy form) {
        logger.info("保存社保补贴表单: {}", form);
        try {
            socialInsuranceService.saveForm(form);
            logger.info("保存成功，返回ID: {}", form.getId());
            return Result.success(form.getId());
        } catch (Exception e) {
            logger.error("保存社保补贴失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    // 提交初创企业社会保险补贴表单
    @PostMapping("/startup-social/submit-direct")
    public Result submitStartupSocial(@RequestBody StartupSocialInsuranceSubsidy form) {
        logger.info("提交社保补贴表单: {}", form);
        try {
            socialInsuranceService.submitForm(form);
            logger.info("提交成功");
            return Result.success();
        } catch (Exception e) {
            logger.error("提交社保补贴失败", e);
            return Result.error("提交失败: " + e.getMessage());
        }
    }

    // 获取用户的初创企业社会保险补贴表单列表
    @GetMapping("/startup-social/list/{username}")
    public Result getStartupSocialList(@PathVariable String username) {
        try {
            List<StartupSocialInsuranceSubsidy> list = socialInsuranceService.getFormsByUsername(username);
            return Result.success(list);
        } catch (Exception e) {
            logger.error("获取社保补贴列表失败: {}", e.getMessage());
            return Result.error("获取列表失败: " + e.getMessage());
        }
    }

    // 获取初创企业社会保险补贴表单详情
    @GetMapping("/startup-social/{id}")
    public Result getStartupSocialDetail(@PathVariable Integer id) {
        try {
            StartupSocialInsuranceSubsidy form = socialInsuranceService.getFormById(id);
            if (form == null) {
                logger.warn("社保补贴表单不存在: ID={}", id);
                return Result.error("表单不存在");
            }
            return Result.success(form);
        } catch (Exception e) {
            logger.error("获取社保补贴详情失败: {}", e.getMessage());
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    // 删除初创企业社会保险补贴表单
    @DeleteMapping("/startup-social/{id}")
    public Result deleteStartupSocial(@PathVariable Integer id) {
        try {
            socialInsuranceService.deleteForm(id);
            logger.info("删除社保补贴表单成功: ID={}", id);
            return Result.success();
        } catch (Exception e) {
            logger.error("删除社保补贴失败: {}", e.getMessage());
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /* ======================= 通用接口 ======================= */

    // 获取用户所有已提交的表单（用于审核结果页面）
    @GetMapping("/submitted-forms/{username}")
    public Result getAllSubmittedForms(@PathVariable String username) {
        try {
            Map<String, List<?>> result = new HashMap<>();
            result.put("highSkillTraining", highSkillService.getAllSubmittedForms(username));
            result.put("awardProject", awardProjectService.getAllSubmittedForms(username));
            result.put("startupSocialInsurance", socialInsuranceService.getAllSubmittedForms(username));
            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取已提交表单失败: {}", e.getMessage());
            return Result.error("获取已提交表单失败: " + e.getMessage());
        }
    }
}